var TypeSelector = Backbone.View.extend({
	initialize : function() {
		this.render();
		this.model.on('change', this.updateMenu, this);
	},
	render : function() {
		var t = this;
		var template = _.template($("#typesel_template").html(), this.model.toJSON());
		this.$el.html(template);
		this.len = $('li ul li', this.$el).length+1;
		this.updateAction();
		$('button', this.$el).click(function() {
			// t.$el.fadeOut();
			t.hide(true);
		})
	},
	updateAction: function(){
		var t = this;
		if (this.len > 1) {
			$('li ul', this.$el).parent().addClass('enable-hover');
			// $('li ul li', this.$el).eq(0).addClass('selected');
			
			$('li > h4', this.$el).parent().click(function() {
				if (!$(this).hasClass('selected')) {
					$('.selected', t.$el).removeClass('selected');
					$(this).addClass('selected');
					$('span > h4', t.$el).text($('h4', this).text());
					ViewData.asset.search.type = $('h4', this).text();
				}

				$('li ul', t.$el).fadeOut(function() {
					$(this).delay(100).queue(function(next) {
						$(this).removeAttr('style');
						next();
					});
				});

			});
			$('b, button', this.$el).show();
		} else {
			$('b', this.$el).hide();
		}
		if (!this.options.closeBtn)
			$('button', this.$el).hide();
	},
	updateMenu : function() {
				
		var arr = this.model.get('val');
		var len = arr.length;
		
		if (len > 1) {
			if(this.$el.is(":hidden"))
				this.$el.show();
			//Utils.updateItems(arr, $('li ul', this.$el), "li > h4");
			//new items are more than old ones
			$('.selected', this.$el).removeClass('selected');
			if (len > this.len) {
				$('li ul', this.$el).append("<li><h4></h4></li>".repeat(len - this.len));
				
			} else if (len < this.len) {
				//new items are less than old ones
				for (var i = this.len - 1; i >= len; i--) {
					$('li h4', this.$el).eq(i).parent().remove();
				}
			}
			
			this.len = len;
			$('li > h4', this.$el).each(function(index) {
				var v = arr[index+1];
				if(v==arr[0])
					$(this).parent().addClass('selected');
				$(this).text(v);
			});
			
		}
		this.updateAction();
		// console.log(arr[0]+','+$('span > h4', this.$el).length)
		$('span > h4', this.$el).text(arr[0]);
		
		// if(len==0) 
			// this.$el.hide();

	},
	hide : function(withAni) {
		if (this.$el.is(":hidden"))
			return;
		if (withAni) {
			this.$el.fadeOut();
		} else {
			this.$el.hide();
		}
		ViewData.asset.search.type = "";
	},
	show : function(withAni) {
		if (this.$el.is(':visible'))
			return;
		if (withAni) {
			this.$el.fadeIn();
		} else {
			this.$el.show();
		}
		ViewData.asset.search.type = this.model.get('val')[0];
	}
});

//for cache used menu items.
var PopupTipItem = (function() {

	var item = function() {
		var html = _.template($("#tipItem_template").html(), ['', ''], {
			variable : 'v'
		});
		this.el = $(html);
		this.typeModel = new ItemModel({
			val : ['']
		});
		this.type = new TypeSelector({
			el : $('.item-wrapper > span.type-wrapper', this.el),
			model : this.typeModel
			// data: {val:['']}
		});
		this.addEvents();

	};

	item.prototype = {
		update : function(m, index) {
			this.model = m;
			$('.item-wrapper', this.el).attr('index', index);
			$('span.tip-val', this.el).text(m.get(0));
			// $('span.tip-val', this.el).attr('ndaid', m.get(1));

			this.typeModel.set('val', [m.get(1)]);
			this.addEvents();

			return this;
		},
		addEvents : function() {
			var t = this;
			$(".item-wrapper", this.el).mouseup(function() {
				$(this).closest('ul').trigger("hide", [t.model, true]);
			}).mousedown(function() {
				t.show();
			}).mouseenter(function() {
				t.show();
				$(this).closest('ul').attr('index', $(this).attr('index'));
			});

		},
		show : function() {
			var t = this;
			var node = $(".item-wrapper", this.el);
			$('.selected', node.closest('ul')).removeClass('selected').trigger("select", this.model);
			node.addClass('selected');
			// ViewData.asset.search = {val:t.model.get(0),type:t.model.get(1)}



			// node.closest('ul').attr('focus', '1')
		}
	}
	return item;
})();

var PopupTipsMenu = Backbone.View.extend({
	initialize : function() {

		this.initCacheItems();
		this.render();
		this.renderSticky();
		this.collection.on("reset", this.reset, this);
		this.collection.on("add", this.addMenu, this);
		this.registerInputEvents();
	},
	reset: function(){
		// if(this.input.val()==)
		this.show();
		this.updateMenu();
	},
	resetCount : function() {
		this.ul.empty();
	},
	initCacheItems : function() {

		this.cache = [];
		this.itemCount = this.options.maxItemCount || 5;

		for (var i = 0; i < this.itemCount; i++) {
			this.cache.push(new PopupTipItem());
		}
	},
	renderSticky : function() {
		// this.stickyData = new ItemModel({
			// val : ['']
		// });
		this.stickyTag = new TypeSelector({
			el : $('.sticky', this.el),
			// closeBtn : true,

			model : ViewData.asset.sticky
			// data: {val:['']}
		});
		this.stickyTag.hide();
	},
	render : function() {
		this.$el.append('<ul class="dropdown-menu tips-menu"></ul>');
		this.updateMenu();
		var input = this.$el.find('input');
		this.input = input;
		this.ul.on({
			hide : function(event, m, withAni) {

				if (m) {
					$(this).attr('set', 1);
					input.trigger("set", m);
				}
				$(this).removeAttr('focus');
				if ($(this).is(":hidden"))
					return;
				if (withAni) {
					$(this).fadeOut(function() {
						$(this).hide()
					});
				} else {
					$(this).hide()
				}
			},
			mouseleave : function() {
				$(this).removeAttr('focus');
				if ($(this).attr('set') != '1') {
					input.trigger("reset");
				} else
					$(this).removeAttr('set');
			},
			mouseenter : function() {
				$(this).attr('focus', 1);
			},
			select : function(event, val) {
				if($(this).is(':animated'))
					return;
				input.trigger("update", val);
			}
		});
	},
	registerInputEvents : function() {
		var tm = this;
		var changeInput = function(val) {
			tm.input.trigger("update", val)
		};
		var timer; 		
		this.input.on({
			update : function(event, m) {
				//t.stickyTag.hide();
				
				$(this).val(m.get(0));
				
				if(ViewData.asset.action == 1){
				// for the new dropdown list
					var newval = [m.get(1)].concat(ViewData.asset.tips_type[m.get(0)]);
					ViewData.asset.sticky.set('val', newval);
					ViewData.asset.search = {val:m.get(0), type: m.get(1)};
					// console.log(m.get(1))
					tm.stickyTag.show(true);
				}
				else{
					ViewData.asset.search = {val:m.get(0)};
				}
			},
			reset : function(event, m) {
				$(this).val($(this).attr('val'));
				if (!$(this).attr('itype')) {
					tm.stickyTag.hide(true);
				} else {
					ViewData.asset.sticky.set('val', [$(this).attr('itype')]);
				}

			},
			set : function(event, m) {
				$(this).val(m.get(0)).attr({
					'val' : m.get(0),
					'itype' : m.get(1)
				});
				tm.hide();
			},
			keydown : function(event) {
				var inp = $(this);
				ViewData.asset.sticky.set("val", "");
				// ViewData.asset.search.type = "";

				switch (event.which) {
					case 38:
						//KEY_UP:
						tm.moveUp(changeInput);
						return;
					case 40:
						//KEY_DOWN:
						tm.moveDown(changeInput);
						return;
				}
				// event.stopImmediatePropagation();
				// event.preventDefault();
			},
			keyup : function(event) {
				var inp = $(this);

				//ViewData.asset.search.val = inp.val().trim();
				switch (event.which) {
					case 38:
					//KEY_UP:
					case 40:
						//KEY_DOWN:
						return;
				}


				inp.attr('val', inp.val());
				switch (event.which) {
					case 27:
						//KEY_ESC:
						inp.trigger('reset');
						tm.hide();
						return;
					case 9:
					//KEY_TAB:
					case 13:
						//KEY_RETURN:
						if (tm.ul.is(':visible'))
							inp.trigger('set', tm.getSelectedModel());

						if (event.which === 9) {
						}
						return;
				}
				tm.stickyTag.hide();
				if (inp.val().trim().length == 0) {
					tm.hide();
					
					return;
				}
				
				clearTimeout(timer);
				timer = setTimeout(
					function () {
						tm.search(inp.val());
					},
					100
				)
				
				
				// var data = [[["I", 123, "RC1"], ["IBM", 1234, "RIC"], ["IACVB", 10234, "EDCOI2D"], ["I4BMDF", 1234, "RIC2"]], [["I1", 123, "RIC1"], ["I2BM", 1234, "RIC"], ["IB3MACVB", 10234, "EDCOI2D"], ["I4BM", 1234, "RIC2"]]];
				// var tips = data[0];
				// tm.collection.reset(tips);
				// if (tips.length > 0) {
					// //this.block = this.$el.closest('.panel-container').parent().css('overflow',"");
					// tm.show();
				// }

				//event.which == 13 )
			},
			blur : function() {
				if (!tm.ul.attr("focus"))
					tm.hide();
			},
			focus : function() {
				if ($(this).val().length > 0) {
					tm.show();
					var inp = $(this)
					$('ul.dropdown-menu li > .selected', this.el).removeClass('selected');
					$('div.item-wrapper', tm.ul).each(function(index){
						if(inp.val() == $('.tip-val',this).text() &&
							$('span > h4',this).text()==$('span > h4',tm.stickyTag.$el).text())
							$(this).addClass('selected');
							
					})
				}
				if($(this).closest('.input-prepend').hasClass('error')){
					$(this).closest('.input-prepend').removeClass('error control-group')
				}
			}
			// ,
			// mouseenter: function(){
				// this.select();
			// },
			// mouseleave: function(){
				// this.blur();
			// }

		});

	},
	search: function(val){
		var v = util.encodeQuery(val);
		if(util.ic[v])
			jsonp.ide_tip(util.ic[v]);
		util.call(util.getUrl("ide", v)+"?callback=util.ic['"+v+"']=jsonp.ide_tip");
	},

	updateMenu : function() {
		var t = this;
		this.ul = $('ul.dropdown-menu', this.el).empty();
		// if(this.collection.length > 0)
		// this.ul.show();
		this.collection.each(function(model, index) {
			if (index > t.itemCount - 1)
				return;
			var s = t.cache[index].update(model, index).el;
			t.ul.append(s);
		});
		this.items = $('li.menu-item', this.ul);
		this.selected = -1;

	},
	addMenu : function(model, col, obj) {
		$('ul.dropdown-menu', this.el).append(this.cache[obj.index].update(model).el);
	},
	show : function() {
		this.ul.fadeIn(function() {
			$(this).show();
		});
	},

	hide : function(m) {
		this.ul.trigger('hide', [m, true]);
		// alert(this.ul.is(':visible'));
	},

	moveUp : function(callback) {
		this.move(false, callback)
	},
	moveDown : function(callback) {
		this.move(true, callback)
	},
	move : function(forward, callback) {
		var hovered = $('ul.dropdown-menu li > .selected', this.el);
		var sel = 0;
		//parseInt(this.ul.attr('index'));
		if (hovered.length == 0) {
			// no hovered item
			sel = forward == true ? 0 : -1;
			//$('ul.dropdown-menu li.menu-item:last-child> .item-wrapper', this.el);
		} else {
			sel = parseInt(hovered.attr('index'));
			hovered.removeClass('selected');
			sel += forward == true ? 1 : -1;
		}
		if (sel < 0)
			sel += this.items.length;
		else if (sel >= this.items.length)
			sel -= this.items.length;

		this.ul.attr('index', sel)
		// this.selected = sel;
		hovered = this.items.eq(sel).children('.item-wrapper');
		hovered.addClass('selected');
		if (callback) {
			callback(this.getModel(sel));
		}
	},
	getModel : function(i) {
		return this.collection.at(i);
	},
	getSelectedModel : function() {
		var i = parseInt(this.ul.attr('index'));
		return this.getModel(i);
	}
});
